package com.acme.bankapp.service.networking.worker;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.service.command.EchoCommand;
import com.acme.bankapp.service.command.ListClientsCommand;
import com.acme.bankapp.service.networking.ServerWorker;
import com.acme.bankapp.service.command.AddClientCommand;
import com.acme.bankapp.service.command.CommandRepository;

import java.io.*;

/**
 * Server worker, which receives input and output streams for interaction with clients
 * @author Gregory Sobko
 */
public class CommandWorker implements ServerWorker {

    private CommandRepository commandRepository;

    /**
     * Constructor takes bank to instantiate commands:<br/>
     * {@link AddClientCommand} and {@link ListClientsCommand}
     * @param bank Bank to work with
     */
    public CommandWorker(Bank bank) {
        this.commandRepository = new CommandRepository();
        this.commandRepository.registerCommand(new AddClientCommand(bank));
        this.commandRepository.registerCommand(new ListClientsCommand(bank));
        this.commandRepository.registerCommand(new EchoCommand());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void doWork(InputStream inputStream, OutputStream outputStream) throws IOException {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream))
        ) {
            String s;
            while ((s = bufferedReader.readLine()) != null) {
                bufferedWriter.write(commandRepository.parseAndExecuteCommand(s).replaceAll("\\n",";"));
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
        }
    }
}
